package com.ithe.gateway.swagger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.Arrays;
import java.util.List;

/**
 * Created by zxd on 2022/5/13
 */
//@Component
//@Primary
public class MySwaggerResourcesProvider implements SwaggerResourcesProvider {

    /**
     * swagger3默认的url后缀
     */
    private static final String SWAGGER3URL = "/v2/api-docs";
    /**
     * 网关路由
     */
    private final RouteLocator routeLocator;

    /**
     * 网关应用名称
     */
    @Value("${spring.application.name}")
    private String self;

    @Autowired
    public MySwaggerResourcesProvider(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    /**
     * 对于gateway来说这块比较重要 让swagger能找到对应的服务
     *
     * @return
     */
    @Override
    public List<SwaggerResource> get() {
//        List<SwaggerResource> resources = new ArrayList<>();
//        List<String> routeHosts = new ArrayList<>();
//
//
//        // 获取所有可用的host：serviceId
//        routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
//                .filter(route -> !self.equals(route.getUri().getHost()))
//                .subscribe(route -> routeHosts.add(route.getUri().getHost()));
//
//
//        List<String>  pathList=new ArrayList<String>();
//
//        routeLocator.getRoutes().filter(route -> route.getPredicate()!=null)
//                .subscribe(route->{
//                    System.out.println(route.getPredicate());
//                });
//
//        // 记录已经添加过的server
//        Set<String> dealed = new HashSet<>();
//        routeHosts.forEach(instance -> {
//            // 拼接url
//            String url = "/" + instance.toLowerCase() + SWAGGER2URL;
//            if (!dealed.contains(url)) {
//                dealed.add(url);
//                SwaggerResource swaggerResource = new SwaggerResource();
//                swaggerResource.setUrl(url);
//                swaggerResource.setName(instance);
//                resources.add(swaggerResource);
//            }
//        });


        return Arrays.asList(
                createSwaggerResource("短信微服务","/sms-api"+SWAGGER3URL,"1.0"),
                createSwaggerResource("用户微服务","/user-api"+SWAGGER3URL,"1.0"),
                createSwaggerResource("商品微服务","/goods-api"+SWAGGER3URL,"1.0")
        );
    }

    public SwaggerResource createSwaggerResource(String name,String url,String version){
        SwaggerResource swaggerResource=new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(url);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }


}

